/*
 * @Author: your name
 * @Date: 2021-02-23 13:35:27
 * @LastEditTime: 2021-03-05 23:34:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /wordGame/assets/Script/core/managers/StoragerManager.ts
 */
import IStore from "../store/IStore";
import { UserStore } from "../store/UserStore";

/**
 * localStorage管理器
 */
export class StoragerManager {
    public static storage_user = 'userData';

    /** map表 */
    public static get storeMap(): Map<string, IStore> { return this._storeMap; }
    private static _storeMap: Map<string, IStore> = new Map<string, any>();
    public static init() {
        let storeList = [
            UserStore.Ins,
        ];
        storeList.forEach((store) => {
            this.collect(store);
        })
        console.log(storeList);


    }
    private static collect(store: IStore) {
        StoragerManager._storeMap.set(store.prefix, store)
        store.init();
    }


    /**
     * 存储本地数据
     * @param upload 是否上传到服务器
     */
    public static save(upload: boolean = false): void {
        let localData: any = {};
        StoragerManager.storeMap.forEach((value, key) => {
            localData[key] = value.save;
        })
        let dataJson = JSON.stringify(localData);
        if (dataJson) {
            localStorage.setItem(StoragerManager.storage_user, dataJson);
        }
        if (upload) {
            /**
             * 上传到服务器
             */
        }
    }
    /** 取出本地数据 */
    public static load(success: Function, fail: Function): void {
        let dataJson = localStorage.getItem(StoragerManager.storage_user);
        if (dataJson) {
            let jsonObj = JSON.parse(dataJson);
            if (jsonObj) {
                console.log(jsonObj);
                StoragerManager.storeMap.forEach((value, key) => {
                    value.parse(jsonObj[key]);
                })
            }
            success && success(true);
        } else {
            console.log('need init userData');
            fail && fail(true);
        }
    }
    /** 清除本地数据 */
    public static clear() {
        localStorage.clear();
    }

}